import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class CorePayService extends BaseService<any> {
  private readonly logger = new Logger(CorePayService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * createRecord (原方法名: create)
   * 对应 PHP: CorePayService_core::create()
   * 逻辑类型: undefined - undefined
   * 注意: 为避免与BaseService方法冲突，已重命名
   */
  async createRecord(site_id: number, main_type: number, main_id: number, money: number, trade_type: number, trade_id: number, body: number) {
    // 基于PHP真实逻辑: create
    // PHP原文: $out_trade_no = create_no();         $data = array(             'site_id' => $site_id,             'money' => $money,             'trade_type' => $tra...
const out_trade_no = create_no(];
        const data = [
            site_id: site_id,
            money: money,
            trade_type: trade_type,
            trade_id: trade_id,
            body: body,
            out_trade_no: out_trade_no,
            main_id: main_id,
            from_main_id: main_id,
            main_type: main_type
        ];
        this.model.create(data);
        return out_trade_no;
    }


    /**
     * 通过业务类型和id查询有效的支付单据
     * @param int site_id
     * @param string trade_type
     * @param int trade_id
     * @return Pay|array|mixed|Model
     */
    async findPayInfoByTrade(int site_id, string trade_type, int trade_id)
    {
        const where = [
            [ 'site_id', '=', site_id ],
            [ 'trade_type', '=', trade_type ],
            [ 'trade_id', '=', trade_id ],
            [ 'status', '<>', PayDict.STATUS_CANCEL ),///不查询已取消的单据
        ];
        return this.model.where(where).append([ 'type_name', 'status_name' )).findOrEmpty(];
    }

    /**
     * 通过交易流水号查询支付
     * @param int site_id
     * @param string out_trade_no
     * @return Pay|array|mixed|Model
     */
    async findPayInfoByOutTradeNo(int site_id, string out_trade_no)
    {
        const where = [
            [ 'site_id', '=', site_id ],
            [ 'out_trade_no', '=', out_trade_no )
        ];
        return this.model.where(where).append([ 'type_name', 'status_name' )).findOrEmpty(];
    }

    /**
     * 通过交易流水号查询支付信息以及支付方式()
     * @param int site_id
     * @param string out_trade_no
     * @param string channel
     * @return * @throws DataNotFoundBusinessException
     * @throws DbBusinessException
     * @throws ModelNotFoundBusinessException
     */
    async getInfoByOutTradeNo(int site_id, string out_trade_no, string channel)
    {
        const where = [
            [ 'site_id', '=', site_id ],
            [ 'out_trade_no', '=', out_trade_no )
        ];
        const pay = this.model.where(where).append([ 'type_name', 'status_name' )).findOrEmpty().toArray(];
        if (!!pay)) {
            //todo  校验场景控制支付方式
            pay[ 'pay_type_list' ] = array_values(( this.corePayChannelService ).getAllowPayTypeByChannel(site_id, channel, pay[ 'trade_type' ))];
  }

  /**
   * findPayInfoByTrade
   * 对应 PHP: CorePayService_core::findPayInfoByTrade()
   * 逻辑类型: undefined - undefined
   */
  async findPayInfoByTrade(site_id: number, trade_type: number, trade_id: number) {
    // 基于PHP真实逻辑: findPayInfoByTrade
    // PHP原文: $where = array(             [ 'site_id', '=', $site_id ],             [ 'trade_type', '=', $trade_type ],             [ 'trade_id', '=', $trade_id ], ...
const where = [
            [ 'site_id', '=', site_id ],
            [ 'trade_type', '=', trade_type ],
            [ 'trade_id', '=', trade_id ],
            [ 'status', '<>', PayDict.STATUS_CANCEL ),///不查询已取消的单据
        ];
        return this.model.where(where).append([ 'type_name', 'status_name' )).findOrEmpty(];
    }

    /**
     * 通过交易流水号查询支付
     * @param int site_id
     * @param string out_trade_no
     * @return Pay|array|mixed|Model
     */
    async findPayInfoByOutTradeNo(int site_id, string out_trade_no)
    {
        const where = [
            [ 'site_id', '=', site_id ],
            [ 'out_trade_no', '=', out_trade_no )
        ];
        return this.model.where(where).append([ 'type_name', 'status_name' )).findOrEmpty(];
    }

    /**
     * 通过交易流水号查询支付信息以及支付方式()
     * @param int site_id
     * @param string out_trade_no
     * @param string channel
     * @return * @throws DataNotFoundBusinessException
     * @throws DbBusinessException
     * @throws ModelNotFoundBusinessException
     */
    async getInfoByOutTradeNo(int site_id, string out_trade_no, string channel)
    {
        const where = [
            [ 'site_id', '=', site_id ],
            [ 'out_trade_no', '=', out_trade_no )
        ];
        const pay = this.model.where(where).append([ 'type_name', 'status_name' )).findOrEmpty().toArray(];
        if (!!pay)) {
            //todo  校验场景控制支付方式
            pay[ 'pay_type_list' ] = array_values(( this.corePayChannelService ).getAllowPayTypeByChannel(site_id, channel, pay[ 'trade_type' ))];
  }

  /**
   * findPayInfoByOutTradeNo
   * 对应 PHP: CorePayService_core::findPayInfoByOutTradeNo()
   * 逻辑类型: undefined - undefined
   */
  async findPayInfoByOutTradeNo(site_id: number, out_trade_no: number) {
    // 基于PHP真实逻辑: findPayInfoByOutTradeNo
    // PHP原文: $where = array(             [ 'site_id', '=', $site_id ],             [ 'out_trade_no', '=', $out_trade_no ]         );         return $this->model->w...
const where = [
            [ 'site_id', '=', site_id ],
            [ 'out_trade_no', '=', out_trade_no )
        ];
        return this.model.where(where).append([ 'type_name', 'status_name' )).findOrEmpty(];
    }

    /**
     * 通过交易流水号查询支付信息以及支付方式()
     * @param int site_id
     * @param string out_trade_no
     * @param string channel
     * @return * @throws DataNotFoundBusinessException
     * @throws DbBusinessException
     * @throws ModelNotFoundBusinessException
     */
    async getInfoByOutTradeNo(int site_id, string out_trade_no, string channel)
    {
        const where = [
            [ 'site_id', '=', site_id ],
            [ 'out_trade_no', '=', out_trade_no )
        ];
        const pay = this.model.where(where).append([ 'type_name', 'status_name' )).findOrEmpty().toArray(];
        if (!!pay)) {
            //todo  校验场景控制支付方式
            pay[ 'pay_type_list' ] = array_values(( this.corePayChannelService ).getAllowPayTypeByChannel(site_id, channel, pay[ 'trade_type' ))];
  }

  /**
   * getInfoByOutTradeNo
   * 对应 PHP: CorePayService_core::getInfoByOutTradeNo()
   * 逻辑类型: undefined - undefined
   */
  async getInfoByOutTradeNo(site_id: number, out_trade_no: number, channel: number) {
    // 基于PHP真实逻辑: getInfoByOutTradeNo
    // PHP原文: $where = array(             [ 'site_id', '=', $site_id ],             [ 'out_trade_no', '=', $out_trade_no ]         );         $pay = $this->model->w...
const where = [
            [ 'site_id', '=', site_id ],
            [ 'out_trade_no', '=', out_trade_no )
        ];
        const pay = this.model.where(where).append([ 'type_name', 'status_name' )).findOrEmpty().toArray(];
        if (!!pay)) {
            //todo  校验场景控制支付方式
            pay[ 'pay_type_list' ] = array_values(( this.corePayChannelService ).getAllowPayTypeByChannel(site_id, channel, pay[ 'trade_type' ))];
  }

  /**
   * getPayStatusByTrade
   * 对应 PHP: CorePayService_core::getPayStatusByTrade()
   * 逻辑类型: undefined - undefined
   */
  async getPayStatusByTrade(site_id: number, trade_type: number, trade_id: number) {
    // 基于PHP真实逻辑: getPayStatusByTrade
    // PHP原文: $where = array(             [ 'site_id', '=', $site_id ],             [ 'trade_type', '=', $trade_type ],             [ 'trade_id', '=', $trade_id ], ...
const where = [
            [ 'site_id', '=', site_id ],
            [ 'trade_type', '=', trade_type ],
            [ 'trade_id', '=', trade_id ),
        ];
        const pay_info = this.model.field('status').where(where).findOrEmpty(];
        if (pay_info.isEmpty()) {
            throw new PayBusinessException('TRADE_NOT_EXIST');//支付单据不存在
  }

  /**
   * getInfoByTrade
   * 对应 PHP: CorePayService_core::getInfoByTrade()
   * 逻辑类型: undefined - undefined
   */
  async getInfoByTrade(site_id: number, trade_type: number, trade_id: number, channel: number, scene: number) {
    // 基于PHP真实逻辑: getInfoByTrade
    // PHP原文: $pay = $this->findPayInfoByTrade($site_id, $trade_type, $trade_id);         if ($pay->isEmpty()) {             //创建新的支付单据             $pay = $this->cr...
const pay = this.findPayInfoByTrade(site_id, trade_type, trade_id);
        if (pay.isEmpty()) {
            //创建新的支付单据
            const pay = this.createByTrade(site_id, trade_type, trade_id);
  }

  /**
   * getPayTypeByTrade
   * 对应 PHP: CorePayService_core::getPayTypeByTrade()
   * 逻辑类型: undefined - undefined
   */
  async getPayTypeByTrade(site_id: number, trade_type: number, channel: number) {
    // 基于PHP真实逻辑: getPayTypeByTrade
    // PHP原文: //todo  校验场景控制支付方式         return array_values(( new CorePayChannelService() )->getAllowPayTypeByChannel($site_id, $channel, $trade_type));     }     ...
//todo  校验场景控制支付方式
        return array_values(( this.corePayChannelService ).getAllowPayTypeByChannel(site_id, channel, trade_type)];
    }

    /**
     * 去支付
     * @param site_id
     * @param trade_type
     * @param trade_id
     * @param type
     * @param channel
     * @param string openid
     * @param string return_url
     * @param string quit_url
     * @param string buyer_id
     * @param string voucher
     * @param int member_id
     * @return mixed
     * @throws DataNotFoundBusinessException
     * @throws DbBusinessException
     * @throws ModelNotFoundBusinessException
     */
    async pay(site_id, trade_type, trade_id, type, channel, string openid, string return_url = '', string quit_url = '', string buyer_id = '', string voucher = '', member_id = 0)
    {
        //检测并创建支付单据
        const pay = this.checkOrCreate(site_id, trade_type, trade_id];
        const out_trade_no = pay[ 'out_trade_no' ];
        const money = pay[ 'money' ];
        const body = pay[ 'body' ];
        const trade_type = pay[ 'trade_type' );
        if (!in_[type, array_column(( this.corePayChannelService ).getAllowPayTypeByChannel(site_id, channel, trade_type), 'key'))) throw new PayBusinessException('PAYMENT_METHOD_NOT_SCENE');//场景不支持
        if (member_id != 0) {
            //更新付款人id
            const pay_info = this.findPayInfoByTrade(site_id, trade_type, trade_id);
            pay_info.save([
                main_id: member_id
            )];
  }

  /**
   * pay
   * 对应 PHP: CorePayService_core::pay()
   * 逻辑类型: undefined - undefined
   */
  async pay(site_id: string, trade_type: string, trade_id: string, type: string, channel: string, openid: string, return_url: string, quit_url: string, buyer_id: string, voucher: string, member_id: string) {
    // 基于PHP真实逻辑: pay
    // PHP原文: //检测并创建支付单据         $pay = $this->checkOrCreate($site_id, $trade_type, $trade_id);         $out_trade_no = $pay[ 'out_trade_no' ];         $money = $p...
//检测并创建支付单据
        const pay = this.checkOrCreate(site_id, trade_type, trade_id];
        const out_trade_no = pay[ 'out_trade_no' ];
        const money = pay[ 'money' ];
        const body = pay[ 'body' ];
        const trade_type = pay[ 'trade_type' );
        if (!in_[type, array_column(( this.corePayChannelService ).getAllowPayTypeByChannel(site_id, channel, trade_type), 'key'))) throw new PayBusinessException('PAYMENT_METHOD_NOT_SCENE');//场景不支持
        if (member_id != 0) {
            //更新付款人id
            const pay_info = this.findPayInfoByTrade(site_id, trade_type, trade_id);
            pay_info.save([
                main_id: member_id
            )];
  }

  /**
   * checkOrCreate
   * 对应 PHP: CorePayService_core::checkOrCreate()
   * 逻辑类型: undefined - undefined
   */
  async checkOrCreate(site_id: any, trade_type: any, trade_id: any) {
    // 基于PHP真实逻辑: checkOrCreate
    // PHP原文: $pay = $this->findPayInfoByTrade($site_id, $trade_type, $trade_id);         if ($pay->isEmpty()) {             //创建新的支付单据             $pay = $this->cr...
const pay = this.findPayInfoByTrade(site_id, trade_type, trade_id);
        if (pay.isEmpty()) {
            //创建新的支付单据
            const pay = this.createByTrade(site_id, trade_type, trade_id);
  }

  /**
   * createByTrade
   * 对应 PHP: CorePayService_core::createByTrade()
   * 逻辑类型: undefined - undefined
   */
  async createByTrade(site_id: any, trade_type: any, trade_id: any) {
    // 基于PHP真实逻辑: createByTrade
    // PHP原文: //创建新的支付单据         $data = array_values(array_filter(event('PayCreate', [ 'site_id' => $site_id, 'trade_type' => $trade_type, 'trade_id' => $trade_id ...
//创建新的支付单据
        const data = array_values(array_filter(event('PayCreate', [ site_id: site_id, trade_type: trade_type, trade_id: trade_id ))))[ 0 ] || [];
        if (!data)) throw new PayBusinessException('PAY_NOT_FOUND_TRADE');//找不到可支付的交易

        if (typeof data[ 'status' )) && data[ 'money' ] == 0) {
            data[ 'status' ] = PayDict.STATUS_FINISH;
            data[ 'status_name' ] = PayDict.getStatus()[ data[ 'status' ] ] || '';
            data[ 'type' ] = PayDict.BALANCEPAY;
            data[ 'type_name' ] = PayDict.getPayType()[ data[ 'type' ] ][ 'name' ] || '';
            return data;
  }

  /**
   * returnTo
   * 对应 PHP: CorePayService_core::returnTo()
   * 逻辑类型: undefined - undefined
   */
  async returnTo(site_id: number, pay_item: number) {
    // 基于PHP真实逻辑: returnTo
    // PHP原文: if (is_object($pay_item)) {             $pay = $pay_item;             $out_trade_no = $pay->out_trade_no;...
if (is_object(pay_item)) {
            const pay = pay_item;
            const out_trade_no = pay.out_trade_no;
  }

  /**
   * close
   * 对应 PHP: CorePayService_core::close()
   * 逻辑类型: undefined - undefined
   */
  async close(site_id: number, out_trade_no: number) {
    // 基于PHP真实逻辑: close
    // PHP原文: $pay = $this->findPayInfoByOutTradeNo($site_id, $out_trade_no);         if ($pay->isEmpty()) throw new PayException('ALIPAY_TRANSACTION_NO_NOT_EXIST')...
const pay = this.findPayInfoByOutTradeNo(site_id, out_trade_no);
        if (pay.isEmpty()) throw new PayBusinessException('ALIPAY_TRANSACTION_NO_NOT_EXIST');
        if (pay[ 'status' ) == PayDict.STATUS_CANCEL) return true;

        if (!in_[pay[ 'status' ), [
            PayDict.STATUS_WAIT,
            PayDict.STATUS_ING
        ))) throw new PayBusinessException('TREAT_PAYMENT_IS_OPEN');
        if (pay[ 'status' ) == PayDict.STATUS_ING) {
            if (!!pay.type)) {
                //尝试取消或关闭第三方支付
                const close = this.pay_event.init(site_id, pay.channel, pay.type).close(out_trade_no);
                if (!close) {//有问题查询第三方订单详情
                    const order = this.pay_event.init(site_id, pay.channel, pay.type).getOrder(out_trade_no);
                    if (!!order)) {
                        if (order[ 'status' ) == OnlinePayDict.SUCCESS) {//如果已支付,就将支付调整为已支付
                            this.paySuccess(site_id, [
                                out_trade_no: out_trade_no,
                                type: pay.type
                            )];
                            return false;
                        }
                    }
                }
            }
  }

  /**
   * closeByTrade
   * 对应 PHP: CorePayService_core::closeByTrade()
   * 逻辑类型: undefined - undefined
   */
  async closeByTrade(site_id: number, trade_type: number, trade_id: number) {
    // 基于PHP真实逻辑: closeByTrade
    // PHP原文: $pay = $this->findPayInfoByTrade($site_id, $trade_type, $trade_id); //        if ($pay->isEmpty()) throw new PayException('ALIPAY_TRANSACTION_NO_NOT_E...
const pay = this.findPayInfoByTrade(site_id, trade_type, trade_id);
//        if (pay.isEmpty()) throw new PayBusinessException('ALIPAY_TRANSACTION_NO_NOT_EXIST');
        if (pay.isEmpty()) return true;
//        if (pay.status == PayDict.STATUS_FINISH) throw new PayBusinessException('DOCUMENT_IS_PAID'];//当前单据已支付
        if (!in_[pay[ 'status' ), [
            PayDict.STATUS_WAIT,
            PayDict.STATUS_ING
        ))) throw new PayBusinessException('IS_PAY_REMOVE_NOT_RESETTING');//只有待支付可以关闭支付
        if (!this.close(site_id, pay[ 'out_trade_no' ))) {
            throw new PayBusinessException('DOCUMENT_IS_PAY_REMOVE');
  }

  /**
   * payNotify
   * 对应 PHP: CorePayService_core::payNotify()
   * 逻辑类型: undefined - undefined
   */
  async payNotify(site_id: any[], out_trade_no: any[], type: any[], params: any[]) {
    // 基于PHP真实逻辑: payNotify
    // PHP原文: $pay = $this->findPayInfoByOutTradeNo($site_id, $out_trade_no);          if ($pay->isEmpty()) throw new PayException('ALIPAY_TRANSACTION_NO_NOT_EXIST'...
const pay = this.findPayInfoByOutTradeNo(site_id, out_trade_no);

        if (pay.isEmpty()) throw new PayBusinessException('ALIPAY_TRANSACTION_NO_NOT_EXIST');
        if (pay[ 'status' ) == PayDict.STATUS_FINISH) throw new PayBusinessException('DOCUMENT_IS_PAID');
        if (pay[ 'status' ) == PayDict.STATUS_CANCEL) throw new PayBusinessException('PAY_IS_REMOVE'];
        const status = params[ 'status' );
        switch (status) {
            case OnlinePayDict.SUCCESS://支付成功
                this.paySuccess(site_id, Object.assign([
                    out_trade_no: out_trade_no,
                    type: type
                ), params)];
                break;
            case OnlinePayDict.CLOSED://支付关闭
                this.payClose(site_id, [
                    out_trade_no: out_trade_no,
                    type: type
                )];
                break;
            case OnlinePayDict.NOTPAY://未支付
                //todo  主动去校验支付状态
                this.check(site_id, [
                    out_trade_no: out_trade_no,
                    type: type
                )];
                break;
  }

  /**
   * notify
   * 对应 PHP: CorePayService_core::notify()
   * 逻辑类型: undefined - undefined
   */
  async notify(site_id: number, channel: number, type: number, action: number) {
    // 基于PHP真实逻辑: notify
    // PHP原文: $callback = function ($out_trade_no, $params) use ($site_id, $type, $action) {             try {                 switch ($action) {                   ...
const callback = function (out_trade_no, params) use (site_id, type, action) {
            try {
                switch (action) {
                    case 'pay'://支付结果通知
                        return this.payNotify(site_id, out_trade_no, type, params);
                    case 'refund':
                        return ( this.coreRefundService ).refundNotify(site_id, out_trade_no, type, params);
                    case 'transfer':
                        return ( this.coreTransferService ).transferNotify(site_id, out_trade_no, params);
                }
                //找不到对应的业务
                return true;
            } catch (PayBusinessException e) {
                return false;
            }
  }

  /**
   * check
   * 对应 PHP: CorePayService_core::check()
   * 逻辑类型: undefined - undefined
   */
  async check(site_id: any[], data: any[]) {
    // 基于PHP真实逻辑: check
    // PHP原文: $out_trade_no = $data[ 'out_trade_no' ];         $pay = $this->findPayInfoByOutTradeNo($site_id, $out_trade_no);         if ($pay->isEmpty()) throw ne...
const out_trade_no = data[ 'out_trade_no' ];
        const pay = this.findPayInfoByOutTradeNo(site_id, out_trade_no);
        if (pay.isEmpty()) throw new PayBusinessException('ALIPAY_TRANSACTION_NO_NOT_EXIST');
        if (pay[ 'status' ) == PayDict.STATUS_FINISH) throw new PayBusinessException('PAY_SUCCESS');//单据已支付
        if (pay[ 'status' ) == PayDict.STATUS_CANCEL) throw new PayBusinessException('PAY_IS_REMOVE');//单据已取消
        //查询第三方支付单据
        const pay_info = this.pay_event.init(site_id, pay.channel, pay.type).getOrder(out_trade_no];
        const type = pay[ 'type' );
        if (!pay_info))
            return false;
        const status = pay_info[ 'status' ];
        switch (status) {
            case OnlinePayDict.SUCCESS://支付成功
                this.paySuccess(site_id, [
                    out_trade_no: out_trade_no,
                    type: type
                )];
                break;
            case OnlinePayDict.CLOSED://支付关闭
                this.payClose(site_id, [
                    out_trade_no: out_trade_no,
                    type: type
                )];
                break;
            case OnlinePayDict.NOTPAY://未支付
                //todo  主动去校验支付状态
                this.check(site_id, [
                    out_trade_no: out_trade_no,
                    type: type
                )];
                break;
  }

  /**
   * paySuccess
   * 对应 PHP: CorePayService_core::paySuccess()
   * 逻辑类型: undefined - undefined
   */
  async paySuccess(site_id: any, params: any) {
    // 基于PHP真实逻辑: paySuccess
    // PHP原文: $out_trade_no = $params[ 'out_trade_no' ];         $pay = $this->findPayInfoByOutTradeNo($site_id, $out_trade_no);         $type = $params[ 'type' ]; ...
const out_trade_no = params[ 'out_trade_no' ];
        const pay = this.findPayInfoByOutTradeNo(site_id, out_trade_no];
        const type = params[ 'type' );
        const trade_type = pay.trade_type;
        const trade_id = pay.trade_id;
        const main_id = pay.main_id;
        const data = [
            pay_time: time(),
            status: PayDict.STATUS_FINISH,
            type: type,
            trade_no: params[ 'trade_no' ] || '',
            voucher: params[ 'voucher' ] || '',
            mch_id: params[ 'mch_id' ] || '',
        ];
        //允许修改的值
        const allow_field = [ 'trade_no', 'voucher', 'status', 'pay_time', 'type', 'mch_id' ];

        // 启动事务
        Db.startTrans(];
        try {
            pay.allowField(allow_field).save(data);
            const result = event('PaySuccess', [ out_trade_no: out_trade_no, trade_type: trade_type, site_id: site_id, trade_id: trade_id, main_id: main_id )];
//            if (!check_event_result(result)) {
//                Db.rollback(];
//                return false;
//            }
            // 提交事务
            Db.commit();
            return true;
  }

  /**
   * payClose
   * 对应 PHP: CorePayService_core::payClose()
   * 逻辑类型: undefined - undefined
   */
  async payClose(site_id: any, data: any) {
    // 基于PHP真实逻辑: payClose
    // PHP原文: $out_trade_no = $data[ 'out_trade_no' ];          Db::startTrans();         try {             $pay = $this->findPayInfoByOutTradeNo($site_id, $out_tra...
const out_trade_no = data[ 'out_trade_no' ];

        Db.startTrans(];
        try {
            const pay = this.findPayInfoByOutTradeNo(site_id, out_trade_no];
            pay.save([
                status: PayDict.STATUS_CANCEL,
                fail_reason: data[ 'reason' ) || ''
            )];

            const result = event('PayClose', [ out_trade_no: out_trade_no, site_id: site_id, trade_type: pay.trade_type, trade_id: pay.trade_id )];
            if (!check_event_result(result)) {
                Db.rollback(];
                return false;
            }
            // 提交事务
            Db.commit();
            return true;
  }
}
